<template>
	<view>
		<!-- 人脸采集 -->
		<view class="camera-box">
			<camera device-position="front" flash="off" binderror="error" class="camera"></camera>
			<view class="face-box">
				<button class="face" type="primary" @click="takePhoto()"> 人脸录入 </button>
			</view>
		</view>
	</view>
</template>

<script>
	/* *************人脸采集*************** */
	export default {
		data() {
			return {
				canIUse: wx.canIUse('button.open-type.getUserInfo'),
			    src:"", //图片的链接
			    baidutoken: '',
			    base64: '',
			    msg: ''
			}
		},
		methods: {
			//拍照
			
			takePhoto() {
				console.log("开始拍照")
				let that = this;
				//拍照
				const ctx = wx.createCameraContext()
				ctx.takePhoto({
					quality: 'high',
					success :(res)=>{
						console.log(res);
						console.log(res.tempImagePath);
						var result = res.tempImagePath;
						console.log(result);
							that.setData({
								src : result //获取图片
							});
							
						//图片base64编码
						wx.getFileSystemManager().readFile({
							filePath: result, //选择图片返回的相对路径
							encoding: 'base64', //编码格式
							success: res => { //成功的回调
								that.setData({
									base64: res.data,
									//需要将人脸的base64位的数据存入数据库
								});
								console.log(res.data);
							}
						})
						this.getBaiduToken();
					} //拍照成功结束
				}) //调用相机结束
	
	
				//失败尝试
				wx.showToast({
					title: '请重试',
					icon: 'loading',
					duration: 500
				})
			},
			error(e) {
				console.log(e.detail)
			},
			getBaiduToken() {
				console.log("执行到getBaiduToken------")
			    var that = this;
			    //acess_token获取,qs:需要多次尝试
			    wx.request({
			      url: 'https://aip.baidubce.com/oauth/2.0/token', //是真实的接口地址
			      data: {
			        grant_type: 'client_credentials',
			        client_id: 'wYvymTEg0CwqnXxFXHSVeZBC', //用你创建的应用的API Key
			        client_secret: 'oGhA8u4wkpckwl0i2F8bmfzssaefk2OG' //用你创建的应用的Secret Key
			      },
			      header: {
			        'Content-Type': 'application/json' // 默认值
			      },
			      success(res) {  
					  console.log(res.data.access_token);
					  that.setData({
						  baidutoken:res.data.access_token //获取到token
					  });
			          
			        that.uploadPhoto();
			      }
			    })
			  },
			  uploadPhoto() {
				  console.log("执行到uploadPhoto----")
			      var that = this;
			      //上传人脸进行注册-----test
			      wx.request({
			        url: 'https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=' + this.baidutoken,
			        method: 'POST',
			        data: {
			          image: this.base64,
			          image_type: 'BASE64',
			          group_id: '27549803', //自己建的用户组id
			          user_id: '1' //这里获取用户昵称
			        },
			        header: {
			          'Content-Type': 'application/json' // 默认值
			        },
			        success(res) {
			         that.setData({
					 msg: res.data.error_msg
					 });
						console.log(res.data.error_msg+"-----");
			         
			          //做成功判断
			          if (that.msg == "pic not has face") {
			            wx.showToast({
			              title: '未捕获到人脸',
			              icon: 'error',
			            })
			          }
			          if (that.msg == 'SUCCESS') {
			            wx.showToast({
			              title: '人脸录入成功',
			              icon: 'success',
			            })
			          }
			        }
			      })
			    },
				setData:function(obj){
				let that = this;    
				let keys = [];    
				let val,data;    
				Object.keys(obj).forEach(function(key){    
				 keys = key.split('.');    
				 val = obj[key];    
				 data = that.$data;    
				 keys.forEach(function(key2,index){    
				     if(index+1 == keys.length){    
				         that.$set(data,key2,val);    
				     }else{    
				         if(!data[key2]){    
				            that.$set(data,key2,{});    
				         }    
				     }    
				     data = data[key2];    
				 })    
				});    
				}
		},
	
	}
	/* ******************************** */
</script>

<style>
	/* 人脸识别 */
	.camera-box {
		width: 100%;
		height: 100vh;
		position: relative;
	}
	
	.camera-box .camera {
		width: 100%;
		height: 100%;
		position: absolute;
		top: 0;
	}
	
	.camera-box .face-box {
		position: absolute;
		width: 100%;
		bottom: 40px;
		padding: 40rpx;
		box-sizing: border-box;
	}
	
	.camera-box .face-box .face {
		width: 100%;
	}
	
</style>